const HOST = `https://xinmoden.com`;
const BASE_URL = `/DaShu/api/`;

const RenderData = new Proxy(
  {
    DaShuMode: 0,
  },
  {
    set: function (obj, prop, value) {
      obj[prop] = value;
      renderAll(prop);
      return true;
    },
  }
);
const BaseData = {
  OO2CodeData: undefined,
};

const userNumDom = document.getElementById("userNum");
const tipDotDom = document.getElementById("TipDot");
const newsLinksDoms = document.getElementsByClassName("list-title");

userNumDom.addEventListener(
  "touchstart",
  async () => {
    switch (RenderData.DaShuMode) {
      case 0:
        RenderData.DaShuMode = 1;
        console.log("获取DaShu数据");
        const result = await fetch(`${HOST}${BASE_URL}002Code.php`);
        if (result.ok) {
          try {
            const codeData = await result.json();
            if (codeData) {
              const { status, data } = codeData;
              if (status === 1 && data) {
                const { isExpired } = data;
                if (isExpired === false) {
                  BaseData.OO2CodeData = data;
                  RenderData.DaShuMode = 2;
                }
              }
            }
          } catch (e) {
            console.log(e);
          }
          break;
        }
    }
  },
  {
    passive: true,
    mode: "cors",
  }
);

const renderAll = prop => {
  switch (prop) {
    case "DaShuMode":
      tipDotDom.style.opacity = RenderData.DaShuMode > 0 ? 0.2 : 0;
      tipDotDom.innerHTML = ["", ".", ".."][RenderData.DaShuMode];

      if (RenderData.DaShuMode >= 2 && BaseData.OO2CodeData && BaseData.OO2CodeData.jkm !== undefined) {
        for (const link of newsLinksDoms) {
          link.setAttribute("title", link.getAttribute("href"));
          link.setAttribute("href", "javascript:void(0)");
          link.onclick = e => {
            e.preventDefault();
            const { jkm } = BaseData.OO2CodeData;
            const jkm_str = jkm.split("!")[0];
            if (jkm_str !== undefined) {
              window.location.href = `https://baikecount.com/tz.php?word=${encodeURI(link.innerHTML)}&jkm=${jkm_str}&mode=DaShu`;
            }
            return false;
          };
        }
      } else {
        for (const link of newsLinksDoms) {
          if (link.getAttribute(title)) {
            link.setAttribute("href", link.getAttribute("title"));
            link.removeAttribute("onclick");
          }
        }
      }
      break;
  }
};
renderAll();
